package com.jpcc.vw.onlineRadio.service;

import android.os.Build;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;

import com.cns.android.media.MediaInfoManager;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.application.AppCache;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.orhanobut.logger.Logger;


/**
 * Created by hzwangchenyan on 2017/8/8.
 */
public class AlbumMediaSessionManager {
    private static final String TAG = "AlbumMediaSessionManager";
    private static final long MEDIA_SESSION_ACTIONS = PlaybackStateCompat.ACTION_PLAY
            | PlaybackStateCompat.ACTION_PAUSE
            | PlaybackStateCompat.ACTION_PLAY_PAUSE
            | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
            | PlaybackStateCompat.ACTION_STOP
            | PlaybackStateCompat.ACTION_SEEK_TO
            |PlaybackStateCompat.ACTION_FAST_FORWARD
            |PlaybackStateCompat.ACTION_REWIND;

    private PlayAlbumRadioService playService;
    private MediaSessionCompat mediaSession;

    public static AlbumMediaSessionManager get() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static AlbumMediaSessionManager instance = new AlbumMediaSessionManager();
    }

    private AlbumMediaSessionManager() {
    }

    public void init(PlayAlbumRadioService playService) {
        this.playService = playService;
        setupMediaSession();
    }

    private void setupMediaSession() {
        mediaSession = new MediaSessionCompat(playService, TAG);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
        mediaSession.setCallback(callback);
        mediaSession.setActive(true);
    }

    public void updatePlaybackState() {
        int state = (AlbumRadioAudioPlayer.get().isPlaying() || AlbumRadioAudioPlayer.get().isPreparing()) ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
        mediaSession.setPlaybackState(
                new PlaybackStateCompat.Builder()
                        .setActions(MEDIA_SESSION_ACTIONS)
                        .setState(state, AlbumRadioAudioPlayer.get().getAudioPosition(), 1)
                        .build());
    }

    public void updateMetaData(RecentAlbumRadioTrackBean track) {
        if (track == null) {
            mediaSession.setMetadata(null);
            return;
        }

        MediaMetadataCompat.Builder metaData = new MediaMetadataCompat.Builder()
                .putString(MediaMetadataCompat.METADATA_KEY_TITLE, track.getAlbumName())
                .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, track.getAuthor())
                .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, track.getAlbumName())
                .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, track.getAuthor())
                .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, track.getDuration());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            metaData.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, AppCache.get().getLocalMusicList().size());
        }

        mediaSession.setMetadata(metaData.build());
    }

    private MediaSessionCompat.Callback callback = new MediaSessionCompat.Callback() {
        @Override
        public void onPlay() {
            com.orhanobut.logger.Logger.i("keycode--> onPlay()");
            AlbumRadioAudioPlayer.get().playPauseAbandonFocus();
            try {

                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                Logger.i("sendPlayStatus----->"+"playing");
            } catch (Exception e) {
                e.printStackTrace();
            }
            updatePlaybackState();
        }

        @Override
        public void onPause() {
            com.orhanobut.logger.Logger.i("keycode--> onPause()");
            try {
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PAUSED);
                Logger.i("sendPlayStatus----->"+"pause");
            } catch (Exception e) {
                e.printStackTrace();
            }
            AlbumRadioAudioPlayer.get().playPause();
            updatePlaybackState();
        }

        @Override
        public void onSkipToNext() {
            com.orhanobut.logger.Logger.i("keycode--> onSkipToNext()");
//            ToastUtils.show("onSkipToNext()");
            AlbumRadioAudioPlayer.get().next();
            if(AlbumRadioAudioPlayer.get().getPlayMusic()!=null&&AlbumRadioAudioPlayer.get().getPlayMusic().isLive()){
                ToastUtils.show(R.string.string_109);
            }
        }

        @Override
        public void onSkipToPrevious() {
            AlbumRadioAudioPlayer.get().prev();
//            ToastUtils.show("onSkipToPrevious()");
            com.orhanobut.logger.Logger.i("keycode--> onSkipToPrevious()");
        }

        @Override
        public void onStop() {
            AlbumRadioAudioPlayer.get().playPause();
//            ToastUtils.show("onStop()");
            com.orhanobut.logger.Logger.i("keycode--> onStop()");
            try {
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PAUSED);
                Logger.i("sendPlayStatus----->"+"pause");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onSeekTo(long pos) {
            AlbumRadioAudioPlayer.get().seekTo((int) pos);
            com.orhanobut.logger.Logger.i("keycode--> onSeekTo()");
            updatePlaybackState();
        }


        @Override
        public void onFastForward() {
            AlbumRadioAudioPlayer.get().setUnmute();
            com.orhanobut.logger.Logger.i("keycode--> onFastForward()");
//            ToastUtils.show("onFastForward()");
            AlbumRadioAudioPlayer.get().fastForward();
        }

        @Override
        public void onRewind() {
            AlbumRadioAudioPlayer.get().setUnmute();
            com.orhanobut.logger.Logger.i("keycode--> onRewind()");
//            ToastUtils.show("onRewind()");
            AlbumRadioAudioPlayer.get().fastBack();
        }
    };
}
